package com.sxt.disruptor.chap01;

import java.nio.ByteBuffer;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.lmax.disruptor.BlockingWaitStrategy;
import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.dsl.Disruptor;
import com.lmax.disruptor.dsl.ProducerType;

/**
 * 	实例化Disruptor实例
 * @author Administrator
 *
 */
public class OrderMain {

	public static void main(String[] args) {
		OrderEventFactory orderEventFactory = new OrderEventFactory();
        int ringBufferSize = 1024 * 1024;//指定容器的大小
        ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()); //指定线程，建议使用自定义线程池

        /**
         * 1.实例化disruptor对象
         * 	参数一：orderEventFactory 消息（event）工厂对象
         * 	参数二：ringBufferSize 容器的长度
         * 	参数三：线程池（建议使用自定义线程池）RejectedExecutionHandler
         * 	参数四：ProducerType 单生产者还是多生产者
         * 	参数五：waitStrategy 等待策略
         */
        Disruptor<OrderEvent> disruptor = new Disruptor<OrderEvent>(orderEventFactory, ringBufferSize, executorService, ProducerType.SINGLE, new BlockingWaitStrategy());

        //2.添加消费者的监听
        disruptor.handleEventsWith(new OrderEventHandler());

        //3.启动disruptor
        disruptor.start();

        //4.获取实际存储数据的容器： RingBuffer
        RingBuffer<OrderEvent> ringBuffer = disruptor.getRingBuffer();

        OrderEventProducer producer = new OrderEventProducer(ringBuffer);

        ByteBuffer byteBuffer = ByteBuffer.allocate(8);

        for (long i = 0; i < 100; i++) {
            byteBuffer.putLong(0, i);
            producer.sendData(byteBuffer);
        }
        disruptor.shutdown();
        executorService.shutdown();
	}

}
